import { ref, onBeforeMount, onUnmounted } from 'vue'

export default function () {
    const chartInstance = ref(null)
    onBeforeMount(() => {
        //注册一个钩子，在组件被挂载之前被调用
        window.addEventListener('resize', resizeHandler)
    })
    /**
     * 防抖
     * @param {function} fn 处理函数
     * @param {number} delay 延迟时间
     * @returns
     */
    function _debounce(fn, delay = 300) {
        var timer = null
        return function () {
            var _this = this
            var args = arguments
            if (timer) clearTimeout(timer)
            timer = setTimeout(() => {
                fn.apply(_this, args)
            }, delay)
        }
    }
    function resizeHandler() {
        _debounce(() => {
            chartInstance.value.resize()
        }, 100)
    }
    // 销毁ECharts实例 销毁实例释放资源，避免内存泄漏
    onUnmounted(() => {
        window.removeEventListener('resize', resizeHandler)
        if (chartInstance.value != null && chartInstance.value.dispose) {
            chartInstance.value.dispose()
        }
    })
    return {
        chartInstance
    }
}
